<template>
  <el-container>
    <el-header class="upload-header">
      <i class="el-icon-video-camera-solid"></i>
      <span style="margin-left: 10px;">Video Trailer Generator</span>
    </el-header>
    <el-main>
      <el-row :gutter="20">
        <el-col :span="15">
          <el-card shadow="always" class="video-card">
            <el-upload
                v-if="!videoUrl"
                class="upload-demo"
                :action="uploadPath"
                :limit="1"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="onSuccess"
                :on-error="onError"
            >
              <el-button size="small" type="primary">Upload Video</el-button>
            </el-upload>
            <!-- 视频预览 -->
            <div v-if="videoUrl" class="video-preview">
              <video :src="videoUrl" controls>
                Your browser does not support video playback。
              </video>
            </div>
            <el-button v-if="videoUrl" class="delete-button" @click="deleteVideo" icon="el-icon-delete">
              remove
            </el-button>
          </el-card>
        </el-col>
        <el-col :span="9">
          <el-card shadow="always" class="form-card">
            <el-form label-position="top" label-width="80px" :model="uploadFormOne" ref="uploadFormOne"
                     :rules="oneRules">
              <el-form-item label="Prompt" prop="prompt">
                <el-input v-model="uploadFormOne.prompt"></el-input>
              </el-form-item>
              <el-form-item label="Desired clip length(seconds)" prop="clip_length">
                <el-slider v-model="uploadFormOne.clip_length" :min="10" :max="30" show-input></el-slider>
              </el-form-item>
              <el-form-item label="Temperature" prop="temperature">
                <el-slider v-model="uploadFormOne.temperature" :step="0.1" :min="0" :max="1" show-input></el-slider>
              </el-form-item>
              <el-form-item style="margin-top: 80px;">
                <el-button v-if="analyzeResult && analyzeResult.segments" type="primary" @click="onSubmit(false)">
                  Regenerate
                </el-button>
                <el-button v-else type="primary" @click="onSubmit(true)">Analyze Video</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="15">
          <el-card shadow="always" class="analyze-card">
            <el-divider content-position="left">Available scenarios</el-divider>
            <el-table
                :data="analyzeResultList"
                border
                empty-text="No analytical data available."
                style="width: 100%">
              <el-table-column prop="title" label="Title" width="160" align="center" fixed="left"/>
              <el-table-column prop="relevance_score" label="Relevance" width="100" align="center"/>
              <el-table-column prop="duration" label="Duration (sec)" width="120" align="center"/>
              <el-table-column prop="scene" label="Scene Description" min-width="220" align="center"/>
              <el-table-column prop="relevance_explanation" label="Relevance Explanation" min-width="220"
                               align="center"/>
              <el-table-column prop="start" label="Start Time" width="160" align="center"/>
              <el-table-column prop="end" label="End Time" width="160" align="center"/>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="9">
          <el-card shadow="always" class="status-card">
            <el-divider content-position="left">Analyze Status</el-divider>
            <div class="status-text">{{ analyzeResult.status || 'Not generated' }}</div>
          </el-card>
          <el-card shadow="always" class="select-card">
            <el-divider content-position="left">Select Scenes for Trailer</el-divider>
            <div class="select-body" v-if="analyzeResult && analyzeResult.extra && analyzeResult.extra.choices">
              <el-checkbox-group v-model="selected_scenes">
                <el-checkbox v-for="(item, index) in analyzeResult.extra.choices" :label="index" :key="index">
                  <el-badge :value="getSelectIndex(index)" class="select-item-title">
                    <div>{{ item }}</div>
                  </el-badge>
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <el-button
                :disabled="!analyzeResult || !analyzeResult.extra || !analyzeResult.extra.choices || !analyzeResult.extra.choices.length"
                type="primary"
                @click="stageTwo"
                style="width: 100%; margin: 20px 0 40px;"
            >
              Generate Trailer
            </el-button>

            <el-divider content-position="left">Generation Status</el-divider>
            <div class="status-text">{{ stageTwoResult.status || 'Not generated' }}</div>

            <el-button
                :disabled="!stageTwoResult.trailer_path"
                type="primary"
                @click="downloadVideo"
                style="width: 100%; margin: 20px 0 40px;"
            >
              Download
            </el-button>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>
<script>
import {getDeviceId} from "@/utils"
import {regenerate_segments, stage_one, stage_two} from "@/api/videoUpload"

export default {
  name: "VideoUpload",
  components: {},
  data() {
    return {
      uploadPath: '/api/uploadfile/123',
      userId: null,
      loading: null,
      videoUrl: null,  // 用于保存视频预览的URL
      videoFile: null,
      uploadFormOne: {
        user_id: null,
        video_path: '',
        prompt: '',
        clip_length: 10,
        temperature: 0.5
      },
      oneRules: {
        user_id: [
          {required: true, message: 'Please input user id', trigger: 'blur'}
        ],
        video_path: [
          {required: true, message: 'Please select a video file', trigger: 'change'}
        ],
        prompt: [
          {required: true, message: 'Please input prompt', trigger: 'blur'}
        ],
        clip_length: [
          {required: true, type: 'number', message: 'clip length must be a number'}
        ],
        temperature: [
          {required: true, type: 'number', message: 'temperature must be a number'}
        ]
      },
      // 分析结果
      analyzeResult: {},
      analyzeResultList: [],
      selected_scenes: [], // 保存选中的场景index
      // 生成输出文件 表单
      stageTwoForm: {
        segments: [],
        selected_scenes: [],
        user_id: '',
        video_path: ''
      },
      stageTwoResult: {}
    };
  },
  async mounted() {
    // 获取浏览器指纹ID作为userId
    this.userId = await getDeviceId();
    this.uploadPath = '/api/uploadfile/' + this.userId;

    // 模拟数据
    // this.userId = 'test-user-123';
    // this.uploadPath = '/api/uploadfile/test-user-123';
    // this.uploadFormOne.video_path = 's1-e1-01.mp4';
    // this.uploadFormOne.prompt = 'Compile the most peaceful and warm moments.';
  },
  methods: {
    onLoading(text) {
      this.loading = this.$loading({
        lock: true,
        text: text || 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    // 上传视频文件 之前
    beforeUpload(file) {
      // 检查文件类型
      const isVideo = file.type.startsWith('video/');
      if (!isVideo) {
        this.$message.error('Please select a video file!');
        return false; // 阻止上传行为
      }
      this.onLoading('Uploading');
    },
    // 上传视频文件 成功
    onSuccess(res, file) {
      const videoFile = file.raw;
      this.videoUrl = URL.createObjectURL(videoFile);
      this.videoFile = videoFile;
      this.uploadFormOne.video_path = videoFile.name;
      this.loading.close();
    },
    // 上传视频文件 失败
    onError() {
      this.loading.close();
    },
    // 删除选择视频
    deleteVideo() {
      this.videoUrl = null;
      this.videoFile = null;
      this.uploadFormOne.video_path = '';
      this.analyzeResult = {};
      this.analyzeResultList = [];
      this.selected_scenes = [];
      this.stageTwoResult = {};
    },
    // 提交 分析视频文件
    onSubmit(isFirst) {
      this.uploadFormOne.user_id = this.userId;
      if (!this.uploadFormOne.video_path) {
        this.$message.error('Please select a video file!');
        return;
      }
      this.$refs['uploadFormOne'].validate((valid) => {
        if (valid) {
          this.onLoading('Analyzing');
          if (isFirst) {
            stage_one(this.uploadFormOne).then(res => {
              this.resultCallback(res)
            }).catch(() => {
              this.loading.close();
            })
          } else {
            regenerate_segments(this.uploadFormOne).then(res => {
              this.resultCallback(res)
            }).catch(() => {
              this.loading.close();
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 处理分析结果
    resultCallback(res) {
      this.loading.close();
      this.analyzeResult = res;
      this.analyzeResultList = res.segments || [];
      if (res.dataframe && res.segments) {
        this.analyzeResultList = res.segments.map((item, index) => {
          item.duration = res.dataframe['Duration (sec)'][index]
          return item;
        })
      }
    },
    getSelectIndex(listIndex) {
      const i = this.selected_scenes.indexOf(listIndex);
      return i > -1 ? i + 1 : '';
    },
    // 生成输出文件
    stageTwo() {
      if (!this.selected_scenes || !this.selected_scenes.length) {
        this.$message.error('Please select at least one scene!');
        return;
      }
      this.onLoading();
      this.stageTwoForm.segments = this.selected_scenes.map(item => {
        let obj = this.analyzeResult.segments[item];
        delete obj.duration;
        return obj
      });
      this.stageTwoForm.selected_scenes = this.selected_scenes.map((item, index) => {
        let str = this.analyzeResult.extra.choices[item];
        return str.replace(/^\d+/, index)
      });
      this.stageTwoForm.user_id = this.userId;
      this.stageTwoForm.video_path = this.uploadFormOne.video_path;
      stage_two(this.stageTwoForm).then(res => {
        this.loading.close();
        this.stageTwoResult = res || {};
      }).catch(() => {
        this.loading.close();
      })
    },
    // 下载视频
    downloadVideo() {
      window.location.href = '/api/download/' + this.userId;
    },
  }
};
</script>

<style scoped>
.upload-header {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #F2F6FC;
  font-size: 25px;
  font-weight: 500;
  padding: 40px 0;
}

.video-card {
  width: 100%;
  height: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.video-preview {
  width: 100%;
  height: 600px;
  padding: 15px;
}

.video-preview video {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.delete-button {
  position: absolute;
  right: 10px;
  top: 10px;
}

.form-card {
  width: 100%;
  height: 600px;
}

.analyze-card {
  width: 100%;
  min-height: 600px;
}

.status-card {
  width: 100%;
  min-height: 130px;
}

.status-text {
  font-size: 16px;
  font-weight: 500;
  padding: 0 10px 10px;
}

.select-card {
  min-height: 450px;
  margin-top: 20px;
}

.el-checkbox {
  width: 100%;
  padding: 10px;
}

.select-item-title {
  width: 100%;
  padding: 0 10px;
  font-size: 16px;
}
</style>
